<template>
  <el-dialog
    v-model="dialogVisible"
    title="新建文件夹"
    width="500px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent="handleSubmit"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入文件夹名称"
          @keyup.enter="handleSubmit"
          @keydown.enter.prevent
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { createFolder } from '@/api/file'

const props = defineProps({
  modelValue: Boolean,
  currentPath: {
    type: String,
    default: '/'
  }
})

const emit = defineEmits(['update:modelValue', 'create-success'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref(null)
const form = ref({
  name: ''
})

const rules = {
  name: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        console.log('Validating folder name:', value)
        if (!value) {
          callback(new Error('请输入文件夹名称'))
        } else if (/[\\/:*?"<>|]/.test(value)) {
          callback(new Error('名称不能包含特殊字符 \\ / : * ? " < > |'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('Creating folder with data:', {
          name: form.value.name,
          path: props.currentPath
        })

        const response = await createFolder({
          name: form.value.name,
          path: props.currentPath
        })
        
        console.log('Create folder response:', response)
        
        ElMessage.success('创建成功')
        emit('create-success')
        dialogVisible.value = false
        form.value.name = ''
      } catch (error) {
        console.error('Create folder error:', error)
        ElMessage.error(error.response?.data?.msg || '创建失败')
      }
    }
  })
}
</script> 